<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<%@page pageEncoding="UTF-8" contentType="text/html; UTF-8" isELIgnored="false" %>
<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>订单管理 - 添加多商品订单</title>
    <!-- 引入jQuery库 -->
    <script src="https://code.jquery.com/jquery-3.6.4.min.js"></script>
    <!-- 引入Font Awesome图标库 -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        /* 基础样式 */
        body { font-family: Arial, sans-serif; margin: 0; padding: 20px; background-color: #f5f5f5; }
        .main { max-width: 1200px; margin: 0 auto; background-color: white; padding: 20px; border-radius: 5px; box-shadow: 0 0 10px rgba(0,0,0,0.1); }
        .optitle { margin-bottom: 20px; padding-bottom: 10px; border-bottom: 1px solid #eee; }
        .title { font-size: 18px; font-weight: bold; color: #333; }
        .content { background-color: #f9f9f9; padding: 20px; border-radius: 5px; margin-bottom: 20px; border: 1px solid #ddd; }
        .box { width: 100%; border-collapse: collapse; }
        .box th, .box td { padding: 10px; text-align: left; border-bottom: 1px solid #ddd; }
        .box th { background-color: #f2f2f2; font-weight: bold; }
        .field { width: 120px; font-weight: bold; }
        .buttons { margin-top: 20px; text-align: center; }
        .input-button { padding: 10px 20px; background-color: #4CAF50; color: white; border: none; border-radius: 3px; cursor: pointer; margin: 0 10px; font-size: 14px; transition: background-color 0.3s; }
        .input-button:hover { background-color: #45a049; }
        .input-button.secondary { background-color: #f44336; }
        .input-button.secondary:hover { background-color: #d32f2f; }
        .input-button.tertiary { background-color: #2196F3; }
        .input-button.tertiary:hover { background-color: #0b7dda; }
        .error { color: red; font-size: 12px; display: block; margin-top: 5px; }
        .form-control { padding: 8px; border: 1px solid #ddd; border-radius: 3px; width: 100%; box-sizing: border-box; }
        .text { padding: 8px; border: 1px solid #ddd; border-radius: 3px; width: 100%; box-sizing: border-box; }

        /* 多商品功能样式 */
        .product-section { margin: 20px 0; }
        .product-list { border-collapse: collapse; width: 100%; margin-bottom: 20px; border: 1px solid #ddd; }
        .product-list th, .product-list td { border: 1px solid #ddd; padding: 10px; text-align: left; }
        .product-list th { background-color: #f2f2f2; }
        .add-row-btn { background-color: #4CAF50; color: white; border: none; padding: 8px 15px; cursor: pointer; border-radius: 3px; margin-bottom: 10px; }
        .add-row-btn:hover { background-color: #45a049; }
        .remove-row-btn { background-color: #f44336; color: white; border: none; padding: 5px 10px; cursor: pointer; border-radius: 3px; }
        .remove-row-btn:hover { background-color: #d32f2f; }
        .total-row { font-weight: bold; background-color: #e6e6e6; }
        .required { color: red; }

        /* 动画和交互效果 */
        .product-row { transition: all 0.3s ease; }
        .product-row:hover { background-color: #f5f5f5; }
        .input-error { border: 1px solid red !important; }

        /* 响应式设计 */
        @media (max-width: 768px) {
            .box th, .box td { display: block; width: 100%; }
            .field { width: 100%; margin-bottom: 5px; }
        }

        /* 提示框样式 */
        .toast {
            position: fixed;
            top: 20px;
            right: 20px;
            background-color: #f44336;
            color: white;
            padding: 15px;
            border-radius: 5px;
            box-shadow: 0 4px 8px rgba(0,0,0,0.2);
            z-index: 1000;
            opacity: 0;
            transition: opacity 0.3s ease;
        }

        /* 加载动画 */
        .spinner {
            display: inline-block;
            width: 20px;
            height: 20px;
            border: 3px solid rgba(255,255,255,.3);
            border-radius: 50%;
            border-top-color: white;
            animation: spin 1s ease-in-out infinite;
            margin-right: 10px;
        }

        @keyframes spin {
            to { transform: rotate(360deg); }
        }
    </style>
</head>
<body>
<div class="main">
    <div class="optitle clearfix">
        <div class="title">账单管理 > 添加多商品订单</div>
    </div>

    <form id="orderForm" name="orderForm" method="post" action="BillServlet">
        <input type="hidden" name="method" value="addMulti">
        <input type="hidden" name="orderItemsJson" id="orderItemsJson">

        <!-- 订单基本信息 -->
        <div class="content">
            <h3><i class="fas fa-info-circle"></i> 订单基本信息</h3>
            <table class="box">
                <tbody>
                <tr>
                    <td class="field">客户：<span class="required">*</span></td>
                    <td>
                        <select name="customerId" id="customerId" class="form-control">
                            <option value="">--请选择客户--</option>
                            <c:forEach items="${customers}" var="customer">
                                <option value="${customer.customerID}">${customer.customerName}</option>
                            </c:forEach>
                        </select>
                        <span id="customerIdError" class="error"></span>
                    </td>
                </tr>
                <tr>
                    <td class="field">支付方式：<span class="required">*</span></td>
                    <td>
                        <select name="paymentMethod" id="paymentMethod" class="form-control">
                            <option value="现金">现金</option>
                            <option value="微信">微信</option>
                            <option value="支付宝">支付宝</option>
                            <option value="银行卡">银行卡</option>
                        </select>
                        <span id="paymentMethodError" class="error"></span>
                    </td>
                </tr>
                <tr>
                    <td class="field">订单日期：<span class="required">*</span></td>
                    <td>
                        <input type="datetime-local" name="orderDate" id="orderDate" value="<fmt:formatDate value="${currentDate}" pattern="yyyy-MM-dd'T'HH:mm" />" class="form-control">
                        <span id="orderDateError" class="error"></span>
                    </td>
                </tr>
                </tbody>
            </table>
        </div>

        <!-- 商品列表区域 -->
        <div class="content product-section">
            <h3><i class="fas fa-boxes"></i> 商品列表 <span class="required">*</span></h3>
            <button type="button" id="addProductBtn" class="add-row-btn">
                <i class="fas fa-plus"></i> 添加商品
            </button>
            <table class="product-list" id="productTable">
                <thead>
                <tr>
                    <th width="25%">商品选择</th>
                    <th width="20%">商品名称</th>
                    <th width="10%">数量</th>
                    <th width="10%">单价</th>
                    <th width="15%">折扣率</th>
                    <th width="10%">单项金额</th>
                    <th width="10%">操作</th>
                </tr>
                </thead>
                <tbody id="productTableBody">
                <!-- 初始商品行 -->
                <tr class="product-row" id="row_0">
                    <td>
                        <select name="productId[]" class="product-select form-control" data-index="0">
                            <option value="">--选择商品--</option>
                            <c:forEach items="${products}" var="product">
                                <option value="${product.productID}" data-name="${product.productName}" data-price="${product.unitPrice}">
                                        ${product.productName} (${product.unitPrice}元)
                                </option>
                            </c:forEach>
                        </select>
                        <span id="productIdError_0" class="error"></span>
                    </td>
                    <td>
                        <input type="text" name="productName[]" class="text product-name form-control" data-index="0" readonly>
                    </td>
                    <td>
                        <input type="number" name="productCount[]" class="text product-count form-control" data-index="0" value="1" min="1">
                        <span id="productCountError_0" class="error"></span>
                    </td>
                    <td>
                        <input type="number" name="unitPrice[]" class="text unit-price form-control" data-index="0" readonly step="0.01">
                    </td>
                    <td>
                        <input type="number" name="discountRate[]" class="text discount-rate form-control" data-index="0" value="0" min="0" max="1" step="0.01" title="0表示无折扣，1表示100%折扣(免费)">
                        <span id="discountRateError_0" class="error"></span>
                    </td>
                    <td>
                        <input type="number" name="lineTotal[]" class="text line-total form-control" data-index="0" readonly step="0.01">
                    </td>
                    <td>
                        <button type="button" class="remove-row-btn" disabled>
                            <i class="fas fa-trash"></i> 删除
                        </button>
                    </td>
                </tr>
                </tbody>
                <tfoot>
                <tr class="total-row">
                    <td colspan="5" class="text-right"><strong>订单总额：</strong></td>
                    <td colspan="2">
                        <span id="totalAmountDisplay" class="text-xl font-bold">0.00</span> 元
                        <input type="hidden" name="totalAmount" id="totalAmount" value="0">
                    </td>
                </tr>
                </tfoot>
            </table>
        </div>

        <!-- 供应商与订单状态 -->
        <div class="content">
            <h3><i class="fas fa-truck"></i> 供应商与订单状态</h3>
            <table class="box">
                <tbody>
                <tr>
                    <td class="field">供应商：<span class="required">*</span></td>
                    <td>
                        <select name="supplierId" id="supplierId" class="form-control">
                            <option value="">--请选择供应商--</option>
                            <c:forEach items="${suppliers}" var="supplier">
                                <option value="${supplier.supplierID}">${supplier.supplierName}</option>
                            </c:forEach>
                        </select>
                        <span id="supplierIdError" class="error"></span>
                    </td>
                </tr>
                <tr>
                    <td class="field">订单状态：</td>
                    <td>
                        <select name="orderStatus" id="orderStatus" class="form-control">
                            <option value="待付款">待付款</option>
                            <option value="已付款">已付款</option>
                            <option value="已发货">已发货</option>
                            <option value="已完成">已完成</option>
                            <option value="已取消">已取消</option>
                        </select>
                    </td>
                </tr>
                <tr>
                    <td class="field">备注：</td>
                    <td>
                        <textarea name="remarks" id="remarks" class="form-control" rows="3" placeholder="可输入订单备注信息"></textarea>
                    </td>
                </tr>
                </tbody>
            </table>
        </div>

        <div class="buttons">
            <button type="button" id="saveOrder" class="input-button">
                <i class="fas fa-save"></i> 保存订单
            </button>
            <button type="button" id="resetForm" class="input-button secondary">
                <i class="fas fa-redo"></i> 重置
            </button>
            <button type="button" id="returnBtn" onclick="history.back(-1)" class="input-button tertiary">
                <i class="fas fa-arrow-left"></i> 返回
            </button>
        </div>
    </form>
</div>

<script type="text/javascript">
    $(document).ready(function() {
        let rowIndex = 0;

        // 初始化商品选择事件（使用事件委托）
        $("#productTableBody").on("change", ".product-select", function() {
            const index = $(this).data("index");
            const productId = $(this).val();
            const selectedOption = $(this).find("option:selected");
            const $row = $(this).closest(".product-row");

            if (productId) {
                const productName = selectedOption.data("name");
                const unitPrice = selectedOption.data("price");

                $row.find(".product-name").val(productName);
                $row.find(".unit-price").val(unitPrice);

                // 自动计算单项金额
                calculateLineTotal(index);
                calculateTotalAmount();

                // 移除错误样式
                $(this).removeClass("input-error");
                $(`#productIdError_${index}`).text("");
            } else {
                $row.find(".product-name").val("");
                $row.find(".unit-price").val("");
                $row.find(".line-total").val("0.00");
            }
        });

        // 数量和折扣率变化事件（使用事件委托）
        $("#productTableBody").on("change keyup", ".product-count, .discount-rate", function() {
            const $input = $(this);
            const index = $input.data("index");

            if ($input.hasClass("product-count")) {
                validateNumberInput(this);
            } else if ($input.hasClass("discount-rate")) {
                validateDiscountInput(this);
            }

            calculateLineTotal(index);
            calculateTotalAmount();
        });

        // 添加商品行
        $("#addProductBtn").click(function() {
            rowIndex++;
            const newRow = `
                <tr class="product-row" id="row_${rowIndex}">
                    <td>
                        <select name="productId[]" class="product-select form-control" data-index="${rowIndex}">
                            <option value="">--选择商品--</option>
                            <c:forEach items="${products}" var="product">
                                <option value="${product.productID}" data-name="${product.productName}" data-price="${product.unitPrice}">
                                    ${product.productName} (${product.unitPrice}元)
                                </option>
                            </c:forEach>
                        </select>
                        <span id="productIdError_${rowIndex}" class="error"></span>
                    </td>
                    <td>
                        <input type="text" name="productName[]" class="text product-name form-control" data-index="${rowIndex}" readonly>
                    </td>
                    <td>
                        <input type="number" name="productCount[]" class="text product-count form-control" data-index="${rowIndex}" value="1" min="1">
                        <span id="productCountError_${rowIndex}" class="error"></span>
                    </td>
                    <td>
                        <input type="number" name="unitPrice[]" class="text unit-price form-control" data-index="${rowIndex}" readonly step="0.01">
                    </td>
                    <td>
                        <input type="number" name="discountRate[]" class="text discount-rate form-control" data-index="${rowIndex}" value="0" min="0" max="1" step="0.01" title="0表示无折扣，1表示100%折扣(免费)">
                        <span id="discountRateError_${rowIndex}" class="error"></span>
                    </td>
                    <td>
                        <input type="number" name="lineTotal[]" class="text line-total form-control" data-index="${rowIndex}" readonly step="0.01">
                    </td>
                    <td>
                        <button type="button" class="remove-row-btn" data-index="${rowIndex}">
                            <i class="fas fa-trash"></i> 删除
                        </button>
                    </td>
                </tr>
            `;

            $("#productTableBody").append(newRow);
            updateRemoveButtonStates();
            calculateTotalAmount();

            // 滚动到新添加的行
            $('html, body').animate({
                scrollTop: $(`#row_${rowIndex}`).offset().top - 100
            }, 500);
        });

        // 删除商品行
        $("#productTableBody").on("click", ".remove-row-btn", function() {
            const $row = $(this).closest(".product-row");
            $row.remove();
            updateRemoveButtonStates();
            calculateTotalAmount();
        });

        // 计算单项金额 - 修复计算逻辑
        function calculateLineTotal(index) {
            const $row = $(`#row_${index}`);
            const count = parseFloat($row.find(".product-count").val()) || 0;
            const price = parseFloat($row.find(".unit-price").val()) || 0;
            const discount = parseFloat($row.find(".discount-rate").val()) || 0;

            // 确保折扣率在0-1之间
            const validDiscount = Math.max(0, Math.min(1, discount));
            const lineTotal = count * price * (1 - validDiscount);

            $row.find(".line-total").val(lineTotal.toFixed(2));

            // 如果折扣率被修正，更新输入框
            if (discount !== validDiscount) {
                $row.find(".discount-rate").val(validDiscount.toFixed(2));
            }

            return lineTotal;
        }

        // 计算订单总额 - 修复总额计算问题
        function calculateTotalAmount() {
            let total = 0;
            $(".product-row").each(function() {
                const $row = $(this);
                const lineTotal = parseFloat($row.find(".line-total").val()) || 0;
                total += lineTotal;
            });

            $("#totalAmount").val(total.toFixed(2));
            $("#totalAmountDisplay").text(total.toFixed(2));

            // 添加动画效果
            $("#totalAmountDisplay").animate({ fontSize: '1.5em' }, 200).animate({ fontSize: '1.25em' }, 200);
        }

        // 更新删除按钮状态
        function updateRemoveButtonStates() {
            const rows = $(".product-row");
            if (rows.length <= 1) {
                rows.find(".remove-row-btn").attr("disabled", true);
            } else {
                rows.find(".remove-row-btn").attr("disabled", false);
            }
        }

        // 数字输入验证
        function validateNumberInput(input) {
            const $input = $(input);
            const index = $input.data("index");
            const value = $input.val();

            if (value === "" || isNaN(parseFloat(value)) || parseFloat(value) <= 0) {
                $(`#productCountError_${index}`).text("请输入大于0的数量");
                $input.addClass("input-error");
                return false;
            } else {
                $(`#productCountError_${index}`).text("");
                $input.removeClass("input-error");
                return true;
            }
        }

        // 折扣率验证
        function validateDiscountInput(input) {
            const $input = $(input);
            const index = $input.data("index");
            const value = parseFloat($input.val());

            if (isNaN(value) || value < 0 || value > 1) {
                $(`#discountRateError_${index}`).text("请输入0到1之间的折扣率");
                $input.addClass("input-error");
                return false;
            } else {
                $(`#discountRateError_${index}`).text("");
                $input.removeClass("input-error");
                return true;
            }
        }

        // 表单提交验证
        $("#saveOrder").click(function() {
            let isValid = true;

            // 验证基本信息
            if ($("#customerId").val() === "") {
                $("#customerIdError").text("请选择客户");
                $("#customerId").addClass("input-error");
                isValid = false;
            } else {
                $("#customerIdError").text("");
                $("#customerId").removeClass("input-error");
            }

            if ($("#paymentMethod").val() === "") {
                $("#paymentMethodError").text("请选择支付方式");
                $("#paymentMethod").addClass("input-error");
                isValid = false;
            } else {
                $("#paymentMethodError").text("");
                $("#paymentMethod").removeClass("input-error");
            }

            if ($("#orderDate").val() === "") {
                $("#orderDateError").text("请选择订单日期");
                $("#orderDate").addClass("input-error");
                isValid = false;
            } else {
                $("#orderDateError").text("");
                $("#orderDate").removeClass("input-error");
            }

            if ($("#supplierId").val() === "") {
                $("#supplierIdError").text("请选择供应商");
                $("#supplierId").addClass("input-error");
                isValid = false;
            } else {
                $("#supplierIdError").text("");
                $("#supplierId").removeClass("input-error");
            }

            // 验证商品列表
            $(".product-row").each(function() {
                const $row = $(this);
                const index = $row.find(".product-select").data("index");

                if ($row.find(".product-select").val() === "") {
                    $(`#productIdError_${index}`).text("请选择商品");
                    $row.find(".product-select").addClass("input-error");
                    isValid = false;
                } else {
                    $(`#productIdError_${index}`).text("");
                    $row.find(".product-select").removeClass("input-error");
                }

                if ($row.find(".product-count").val() === "" || isNaN(parseFloat($row.find(".product-count").val())) || parseFloat($row.find(".product-count").val()) <= 0) {
                    $(`#productCountError_${index}`).text("请输入大于0的数量");
                    $row.find(".product-count").addClass("input-error");
                    isValid = false;
                } else {
                    $(`#productCountError_${index}`).text("");
                    $row.find(".product-count").removeClass("input-error");
                }

                if (isNaN(parseFloat($row.find(".discount-rate").val())) || parseFloat($row.find(".discount-rate").val()) < 0 || parseFloat($row.find(".discount-rate").val()) > 1) {
                    $(`#discountRateError_${index}`).text("请输入0到1之间的折扣率");
                    $row.find(".discount-rate").addClass("input-error");
                    isValid = false;
                } else {
                    $(`#discountRateError_${index}`).text("");
                    $row.find(".discount-rate").removeClass("input-error");
                }
            });

            if (isValid) {
                // 收集商品信息
                const orderItems = [];
                $(".product-row").each(function() {
                    const $row = $(this);
                    orderItems.push({
                        productId: $row.find(".product-select").val(),
                        productName: $row.find(".product-name").val(),
                        productCount: $row.find(".product-count").val(),
                        unitPrice: $row.find(".unit-price").val(),
                        discountRate: $row.find(".discount-rate").val(),
                        lineTotal: $row.find(".line-total").val()
                    });
                });

                $("#orderItemsJson").val(JSON.stringify(orderItems));
                $("#orderForm").submit();
            }
        });

        // 重置表单
        $("#resetForm").click(function() {
            $("#orderForm")[0].reset();
            $(".error").text("");
            $(".input-error").removeClass("input-error");
            $("#productTableBody").html(`
                <tr class="product-row" id="row_0">
                    <td>
                        <select name="productId[]" class="product-select form-control" data-index="0">
                            <option value="">--选择商品--</option>
                            <c:forEach items="${products}" var="product">
                                <option value="${product.productID}" data-name="${product.productName}" data-price="${product.unitPrice}">
                                    ${product.productName} (${product.unitPrice}元)
                                </option>
                            </c:forEach>
                        </select>
                        <span id="productIdError_0" class="error"></span>
                    </td>
                    <td>
                        <input type="text" name="productName[]" class="text product-name form-control" data-index="0" readonly>
                    </td>
                    <td>
                        <input type="number" name="productCount[]" class="text product-count form-control" data-index="0" value="1" min="1">
                        <span id="productCountError_0" class="error"></span>
                    </td>
                    <td>
                        <input type="number" name="unitPrice[]" class="text unit-price form-control" data-index="0" readonly step="0.01">
                    </td>
                    <td>
                        <input type="number" name="discountRate[]" class="text discount-rate form-control" data-index="0" value="0" min="0" max="1" step="0.01" title="0表示无折扣，1表示100%折扣(免费)">
                        <span id="discountRateError_0" class="error"></span>
                    </td>
                    <td>
                        <input type="number" name="lineTotal[]" class="text line-total form-control" data-index="0" readonly step="0.01">
                    </td>
                    <td>
                        <button type="button" class="remove-row-btn" disabled>
                            <i class="fas fa-trash"></i> 删除
                        </button>
                    </td>
                </tr>
            `);
            rowIndex = 0;
            calculateTotalAmount();
        });
    });
</script>
</body>
</html>